/********************************************************************************
  * @file    showcolorlineedit.cpp
  * @author  Lun Li
  * @version V1.5.0
  * @date    2022.4.10
  * @brief   This file provides all the ShowColorLineEdit functions.
  ******************************************************************************/

#include "showcolorlineedit.h"

#include <QAction>
#include <QColorDialog>
#include <QIcon>
#include <QLabel>
#include "nomarginlayout.h"

ShowColorLineEdit::ShowColorLineEdit(const QString &labelText, const QColor &color, const QString &text, QWidget *parent)
    : QWidget(parent),
      m_color(color)
{
    QLabel *label = new QLabel(labelText);
    m_lineEdit = new QLineEdit(text);
    setLayout(new NoMarginVBoxLayout);
    layout()->addWidget(label);
    layout()->addWidget(m_lineEdit);
    initialize(color);
}

ShowColorLineEdit::ShowColorLineEdit(const QColor &color, const QString &text, QWidget *parent)
    : QWidget(parent),
      m_color(color)
{
    m_lineEdit = new QLineEdit(text);
    setLayout(new NoMarginVBoxLayout);
    layout()->addWidget(m_lineEdit);
    initialize(color);
}

const QColor &ShowColorLineEdit::color() const
{
    return m_color;
}

void ShowColorLineEdit::initialize(const QColor &color)
{
    QPalette palette;
    palette.setBrush(QPalette::Text, QBrush(color, Qt::DiagCrossPattern));
    m_lineEdit->setPalette(palette);
    m_lineEdit->setReadOnly(true);
    QPixmap pixmap(height(), height());
    pixmap.fill(color);
    QAction *action = new QAction(QIcon(pixmap), QString(), this);
    m_lineEdit->addAction(action, QLineEdit::LeadingPosition);
    connect(action, &QAction::triggered, this, [=]() {
        QColor newColor = QColorDialog::getColor(m_color, this, tr("Set Color"));
        if (newColor.isValid()) {
            m_color = newColor;
            emit colorChanged();
            QPalette palette;
            palette.setBrush(QPalette::Text, QBrush(newColor, Qt::DiagCrossPattern));
            m_lineEdit->setPalette(palette);
            QPixmap pixmap(height(), height());
            pixmap.fill(newColor);
            action->setIcon(QIcon(pixmap));
        }
    });
}
